from  flask import Flask
from  flask import request
import json
#解决跨域问题
from flask_cors import CORS
import hashlib
import pymysql
#引用时间库
from datetime import datetime
from datetime import date

import json
#时间序列化的类
class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)


app=Flask(__name__)
cors=CORS(app)
#数据库连接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='root',
    database='shop'
)
@app.route("/")
def index():
    return "(a:1,b:2)"
#登录
@app.route("/user/login",methods=["POST"])
def login():
    #获取输入的账号和密码
    xuehao = request.json.get("xuehao")
    password = request.json.get("password")
    #加密密码
    password = hashlib.sha1(password.encode()).hexdigest()
    # 数据库连接实例化
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    query = cursor.execute("SELECT * FROM `user_fil` where `xuehao`='"+xuehao+"' and `password`='"+password+"'")
    #result就是查询数据库查询结果
    #, "test": json.dumps(result, cls=CJsonEncoder)
    result = cursor.fetchall()
    returnmsg={"status": 0, 'desc': "登录成功!", 'uid': 1}
    #判断当返回的长度是0的时候，登录失败
    if(len(result) == 0):
        returnmsg["status"] = 1
        returnmsg["desc"] = "用户名和密码不匹配"
        returnmsg["uid"] = 0
    else:
        returnmsg["uid"]=result[0]["uid"]
        returnmsg["info"]=result[0]
    return json.dumps(returnmsg, cls=CJsonEncoder)

@app.route("/goods/lists")
def get_type_lists():
    # 商品类目查询
    cursor=conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("select type_id,type_name from goods_type_fil order by order_by")
    types=cursor.fetchall()
    #查询所有商品
    cursor=conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("select * from goods_fil")
    result=cursor.fetchall()
    for p in types:
        p["data"]=[one for one in result if one["type_id"]==p["type_id"]]
    return json.dumps(types,cls=CJsonEncoder)


app.run(host="192.168.1.101",port=4444,debug=True)